<template>
  <div class="add-book-form">
    <el-card shadow="hover">
      <div slot="header">
        <span>添加新图书</span>
      </div>
      <el-form 
        :model="bookForm" 
        :rules="rules" 
        ref="bookForm" 
        label-width="100px"
      >
        <el-form-item label="书名" prop="title">
          <el-input v-model="bookForm.title"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="bookForm.author"></el-input>
        </el-form-item>
        <el-form-item label="库存数量" prop="copies">
          <el-input-number 
            v-model="bookForm.copies" 
            :min="1" 
            :max="100"
          ></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">添加</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'AddBookForm',
  data() {
    return {
      bookForm: {
        title: '',
        author: '',
        copies: 1
      },
      rules: {
        title: [
          { required: true, message: '请输入书名', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.bookForm.validate((valid) => {
        if (valid) {
          this.$emit('add-book', this.bookForm)
          this.resetForm()
        } else {
          return false
        }
      })
    },
    resetForm() {
      this.$refs.bookForm.resetFields()
    }
  }
}
</script>

<style scoped>
.add-book-form {
  margin-bottom: 20px;
}
</style>